﻿using EasyXaf.LowCode.RulesEngineEditors.UndoManagers.Commands;
using System.Collections;

namespace EasyXaf.LowCode.RulesEngineEditors.UndoManagers.Transactions;

public class Transaction : ICommandTransaction
{
    private readonly Stack<ICommand> _commands = new();
    private readonly ITransactionManager _owner;

    public string ActionName { get; set; }

    public Transaction(ITransactionManager transactionManager)
    {
        _owner = transactionManager ?? throw new ArgumentNullException(nameof(transactionManager));
    }

    public void RegisterCommand(ICommand command)
    {
        _commands.Push(command ?? throw new ArgumentNullException(nameof(command)));
    }

    public void Commit()
    {
        _owner.CommitTransaction(this);
    }

    public void Rollback()
    {
        _owner.RollbackTransaction(this);
    }

    public void Invoke()
    {
        while (_commands.Any())
        {
            _commands.Pop().Invoke();
        }
    }

    public IEnumerator<ICommand> GetEnumerator()
    {
        return _commands.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void Dispose()
    {
        Commit();
        GC.SuppressFinalize(this);
    }
}
